<?php

namespace addons\navigation\controllers;
use addons\navigation\models\NavigationModel;
use controllers\AdminApi;

class index extends AdminApi {
	protected $allField = false;
    /**
     * 初始化
     */
    public function onStepUp(){
        $this->model = new NavigationModel();
    }

    /**
     * 分类接口
     * @param string $title
     * @return array
     */
    public function index($title = '') {
        $map = [];
        if ($title){
            $map['title like'] = $title;
            $field = 'id,title,pid,url,sort,create_time';
			$list = $this->model->where($map)->field($field)->order('sort desc')->select();
			return self::returnJson($list);
        }
        $data = [];
        $this->allField = true;
        $this->getTree($data);
        foreach ($data as &$val){
        	$val['title'] = $val['name'];
        	$val['create_time'] = timeFormat($val['create_time']);
        	unset($val['name']);
		}
        return self::returnJson($data);
    }

	protected function onFind(){
    	$sub = self::$get['sub'];
        $find = $this->getFind();
        if (!$find) $find = [];
        !$sub && $tree = [['id' => 0 , 'name' => '顶级']];
        if ($sub){
        	return [
        		['id' => $find['id'] , 'name' => $find['title'] , 'selected' => true]
			];
		}
        $this->getTree($tree , 0);
        if ($find['pid'] == 0){
        	// 选中顶级
			$find['id'] = 0;
		}else{
        	$find && $find['id'] = $find['pid'];
		}
        foreach ($tree as &$val){
        	$val['selected'] = $find['id'] == $val['id'];
		}
        return $tree;
    }

	/**
	 * 获取导航树
	 * @param array $data
	 * @param int $pid
	 * @param int $deep
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-27 下午8:58
	 */
    protected function getTree(&$data = [] , $pid = 0 , $deep = 0){
    	$map = ['pid' => $pid];
    	$field = $this->allField == true ? 'id,title as name,pid,url,sort,create_time' : 'id,title as name';
		$list = $this->model->where($map)->field($field)->order('sort desc')->select();
		foreach ($list as &$val){
			$val['name'] = str_pad('' , $deep , '-') . $val['name'];
			$val['deep'] = $deep;
			array_push($data , $val);
			$this->getTree($data , $val['id'] , $deep + 3);
		}
	}

	/**
	 * 设置弹窗标题
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setPageTitle() {
		return '导航';
	}

	/**
	 * 设置面包屑
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setCrumbs() {
		return ['导航管理' , '导航列表'];
	}
}
